<!DOCTYPE HTML>
<html>
<!--         
Itec 472 Software Engineering III

Project: Calorie Counter

Authors:
Chris Anderson
Jamie Rouse
Adam Moore
Brandan Griffin

Date: December 4, 2013

This program alllows users to intuitivly monitor their daily calories.
 -->
<head>
    <title>Calorie Counter</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" type="text/css" href="jquery/css/jquery.mobile-1.3.2.min.css" />

    <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
    <script type="text/javascript" charset="utf-8" src="jquery/jquery-2.0.3.min.js"></script>
    <script type="text/javascript" charset="utf-8" src="jquery/jquery.mobile-1.3.2.min.js"></script>
    <script type="text/javascript" charset="utf-8" src="smsplugin.js"></script>

    <script type="text/javascript">
        var db = openDatabase("Test", "1.0", "Test", 65535); //for the application database file

        //Add a listener for the Device Ready event and call the onDeviceReady function
        document.addEventListener("deviceready", onDeviceReady, true);

        //Populates the profile names for the drop down list.
        $(document).on('pageshow', '#pg_page1',
            function () {
                var name;
                var opt;
				
				//reset the current profile as empty string for fresh start from app's first page 
				$("#current_profile").val(""); 
				
                db.transaction(
                    function (transaction) {
                        var sql = 'SELECT Name FROM Profiles';

                        transaction.executeSql(sql, [],
                            function (transaction, result) {
                                $("#slct_profile").children().remove().end().append('<option value="none" disabled = "true">Profile Menu</option>');
                                for (var i = 0; i < result.rows.length; i++) {
                                    name = result.rows.item(i).Name;
									
                                    opt = '<option value="' + name + '">' + name + '</option>';
									
                                    $("#slct_profile").append(opt);
                                }
                                $("#slct_profile").selectmenu("refresh", true);
                            },
                            displayDbError
                        );
                    }
                );
            }
        );
		
		
		 //Populates the list views and date on Foods Eaten page.
        $(document).on('pageshow', '#pg_foodseaten',
            function () {
                var name;
                var calories;
                var type;
                var id;
                var foodEaten;

                $("#breakfastEaten").children().remove().end();
                $("#lunchEaten").children().remove().end();
                $("#dinnerEaten").children().remove().end();
                $("#snacksEaten").children().remove().end();
				
				$.mobile.activePage.find('.ui-btn-active').removeClass('ui-btn-active ui-focus');

                var displayedDateString = getFormattedDateString("header", getDisplayedDate());
				
                if (displayedDateString == "1/1/1") {
                    var today =  new Date();
					$("#txt_eaten_date").html(getFormattedDateString("header", today));
                }

                db.transaction(
                    function (transaction) {
                        var dateString =  getFormattedDateString("db", getDisplayedDate());
                        var owner = document.getElementById("txt_profile_home_name").innerHTML; //for the profile related to the food
						var sql = 'SELECT * FROM Eaten WHERE EatenDate = ? AND ProfileName = ? ORDER BY FoodName';
						var calorieSum = 0;
						
                        transaction.executeSql(sql, [dateString, owner],
                            function (transaction, result) {
                                for (var i = 0; i < result.rows.length; i++) {
                                    name = result.rows.item(i).FoodName;
                                    calories = result.rows.item(i).Calories;
                                    type = result.rows.item(i).Type;
                                    id = result.rows.item(i).ID;

                                    foodEaten = '<li onclick="deleteFromFoodsEaten(\'' + id + '\')">' + name +
                                                  ' - ' + calories + ' calories</li>';

                                    if (type == "breakfast") {
                                        $("#breakfastEaten").append(foodEaten);
                                    }
                                    else if (type == "lunch") {
                                        $("#lunchEaten").append(foodEaten);
                                    }
                                    else if (type == "dinner") {
                                        $("#dinnerEaten").append(foodEaten);
                                    }
                                    else {
                                        $("#snacksEaten").append(foodEaten);
                                    }
									
									calorieSum = calorieSum + Number(calories);
                                }
								
								setRemaining(calorieSum);
								
                                $("#breakfastEaten").listview("refresh", true);
                                $("#lunchEaten").listview("refresh", true);
                                $("#dinnerEaten").listview("refresh", true);
                                $("#snacksEaten").listview("refresh", true);
                            },
                            displayDbError
                        );
                    }
                );
            }
        );
		
		
		/*
        The setRemaining function sets the calories remaining field on the Foods Eaten page.
		
		@param   calSum   the integer that is the summ of calories consumed for the listed date used to determine field 
        */
        function setRemaining(calSum) {
			var record;
			var name = $("#current_profile").val();
							
			db.transaction(
				function (transaction) {
					var sql = 'SELECT * FROM Profiles WHERE Name = ?';
					var goalCals;
					var calsRemaining;
					
					transaction.executeSql(sql, [name],
						function (transaction, result) {
							if (result.rows.length > 0) {
								record = result.rows.item(0);

								goalCals = record.GoalCals;
								
								if(calSum < goalCals){
									calsRemaining = goalCals - calSum;
									$("#spn_foodseaten_calories_remaining").html(calsRemaining);			
								}
								else{
									calsRemaining = "0";
									$("#spn_foodseaten_calories_remaining").html(calsRemaining);
								}
								
								setFoodsEatenAlert(calsRemaining);
							}
							else {
								alert("Profile for " + name + " not found");
							} 
						},
						displayDbError
					);
				}
			);
        }
		
		
		/*
        The setFoodsEatenAlert function sets the alert view according to the calories remaining and calorie goal.
		
		@param  cal  the integer that represent the calories remaining according to goal  
        */
		function setFoodsEatenAlert(cal) {
			if(cal == "0" && $("#goal").val() == "lose"){
				document.getElementById('p_exceed_foodseaten').style.display = 'block';
				document.getElementById('p_unmet_foodseaten').style.display = 'none';
			}			
			else if(cal != "0" && $("#goal").val() == "gain"){
				document.getElementById('p_unmet_foodseaten').style.display = 'block';
				document.getElementById('p_exceed_foodseaten').style.display = 'none';
			}
			else{
				document.getElementById('p_exceed_foodseaten').style.display = 'none';
				document.getElementById('p_unmet_foodseaten').style.display = 'none';
			}			
		}
		
		
        //Populates the list view on Food Selection dialog.
        $(document).on('pageshow', '#pg_eaten_dialog',
            function () { 
                $("#ul_eatenlist").children().remove().end();
                				
                db.transaction(
                    function (transaction) {
						var owner = document.getElementById("txt_profile_home_name").innerHTML;
                        var sql = 'SELECT * FROM Foods WHERE Owner = ? ' + 
								  'UNION ' +
								  'SELECT * FROM Foods WHERE Name NOT IN ' + 
								  '	(SELECT Name FROM (SELECT * FROM Foods WHERE Owner = ? )) ' + 
								  'ORDER BY Name ';

                        transaction.executeSql(sql, [owner, owner],
                            function (transaction, result) {
								var opt;
								var foodId;
                                var name;
                                var calories;
                                
								for (var i = 0; i < result.rows.length; i++) {
									foodId = result.rows.item(i).FoodID;
                                    name = result.rows.item(i).Name;
                                    calories = result.rows.item(i).Calories;

                                    opt = '<li onclick="setSelectedFood(\'' + foodId + 
									'\')"><a href="#pg_type_dialog" data-rel="dialog" data-transition="none" >' +
									name + ' - ' + calories + ' cal</a></li>';
                                    
									$("#ul_eatenlist").append(opt);
                                }
                                $("#ul_eatenlist").listview("refresh", true);
                            },
                            displayDbError
                        );
                    }
                );                
            }
        );
		
		
		
		/*
		The resetFoodsEatenDate function resets the Foods Eaten page to today's date.
		*/
        function resetFoodsEatenDate() {
			$("#txt_eaten_date").html("01/01/0001");
			
			$.mobile.changePage("#pg_foodseaten", { allowSamePageTransition: true, transition: "none", changeHash: "false" });
        }
		

        /*
		The setSelectedFood function sets what food was last selected from the food selection using a hidden input field.
		
		@param   name   the string representing the selected food's name
		*/
        function setSelectedFood(foodId) {
			db.transaction(
				function (transaction) {
					var record;
					var sql = 'SELECT * FROM Foods WHERE FoodID = ? ';
					
					
					transaction.executeSql(sql, [foodId],
						function (transaction, result) {
							if (result.rows.length > 0) {
								record = result.rows.item(0);
		
								$("#selected_food").val(record.Name + ',' + record.Calories);
							}
						},
						displayDbError
					);
				}
			);        
		}


        /*
		The addSelectedToEaten function adds selected to listed date's calories.
		*/
        function addSelectedToEaten(type) {            
            var profileName = document.getElementById("txt_profile_home_name").innerHTML;
            var dateString = getFormattedDateString("db", getDisplayedDate());
			var foodRecordElements = document.getElementById("selected_food").value.split(",");
			var foodName = foodRecordElements[0];
			var calories = foodRecordElements[1];			
			
			db.transaction(
				function (transaction) {
					var sql = 'INSERT INTO Eaten(ProfileName, FoodName, Type, Calories, EatenDate) ' +
							  'VALUES(?, ?, ?, ?, ?) ';

					transaction.executeSql(sql, [profileName, foodName, type, calories, dateString],
						function () {
							alert("Food added to calories");
							$.mobile.changePage("#pg_foodseaten", { allowSamePageTransition: true, transition: "none", changeHash: "false" });
						}
					);
				}, displayDbError
			);
		}
		
				
        /*
        The changeDate function changes the date displayed in the Foods Eaten page's header by 1 day either in the previous or next direction.
		
		@param  dateChange  the string indicating the direction of the date change (i.e. next or previous)
        */
        function changeDate(dateChange) {
            var displayDate = getDisplayedDate(); //for the Date instance that is to be changed
           
            if (dateChange == "next") {
                displayDate.setDate(displayDate.getDate() + 1);
            }            
			if(dateChange == "previous"){
                displayDate.setDate(displayDate.getDate() - 1);
            }
			
			//Set date in header accordingly
            $("#txt_eaten_date").html(getFormattedDateString("header", displayDate));
            
			$.mobile.changePage("#pg_foodseaten", { allowSamePageTransition: true, transition: "none", changeHash: "false" });
        }
		
		
		/*
        The getDisplayedDate function returns the date object related to the date displayed in the Foods Eaten page's header.
        */
		function getDisplayedDate() {
			var displayedDate =  document.getElementById("txt_eaten_date").innerHTML; //for the string representation of the Date returned
			var aDate = new Date(); //for Date instance returned
			var dateElements = displayedDate.split("/"); //for the parameters used to set the returned Date
			
            aDate.setFullYear(dateElements[2], (dateElements[0] - 1), dateElements[1]); //set Date to be returned
			
			return aDate;
		}
		
		
		/*
        The getFormattedDateString function returns a string representation of Date object passed accordingly.
		
		@param   format   a string that is either header or db to indicate the format of returned date string 
		@param   aDate    the date instance used to create date string
		
		@return  formattedDateString   the formatted string represented the Date object passed 
        */
		function getFormattedDateString(format, aDate) {
			var formattedDateString; //to hold the date string returned
            var dd = aDate.getDate(); //for the day of the month string used in date string
            var mm = aDate.getMonth() + 1; //for the month string used in date string
            var yyyy = aDate.getFullYear(); //for the year string used in date string
			
			if(format == "header"){
				formattedDateString = mm + "/" + dd + "/" + yyyy;
			}			
			if(format == "db"){
				formattedDateString =  yyyy + "-" + mm + "-" + dd;			
			}
            return formattedDateString;
        }
		
		
		/*
        The deleteFromFoodsEaten function removes foods selected from the menu for the date listed.
        */
        function deleteFromFoodsEaten(id) {
            //Request delete confirmation
            var dlte = confirm('Are you sure you want to remove that food from the menu?');

            //Delete if confirmed
            if (dlte == true) {
                db.transaction(
					function (transaction) {
						var sql = 'DELETE FROM Eaten WHERE ID = ?; ';

						transaction.executeSql(sql, [id],
							function () {
								$.mobile.changePage("#pg_foodseaten", { allowSamePageTransition: true, transition: "none", changeHash: "false" });
							},
							displayDbError
						);
					}
				);
            }
        }

		
        //Populates the Manage Foods page.
        $(document).on('pageshow', '#pg_managefoods',
			function () {
				//Reset form if no action or food for edit/delete is registerd
			    if (document.getElementById("food_action") != "" ||
					document.getElementById("update_food") != "") {

			        resetFoodForm();

			        document.getElementById("update_food").value = "";
			        document.getElementById("food_action").value = "";
			    }

			    document.getElementById('div_foodlist').style.display = 'none'; //hide list view on page
			    $.mobile.activePage.find('.ui-btn-active').removeClass('ui-btn-active ui-focus');

			    $("#ul_foodlist").children().remove().end();

			    db.transaction(
					function (transaction) {
						var foodID;
						var name;
						var calories;
						var owner;
						var opt;
						var profileName = document.getElementById("txt_profile_home_name").innerHTML;
					    var sql = 'SELECT * FROM Foods WHERE Owner = ? ORDER BY Name';

					    transaction.executeSql(sql, [profileName],
							function (transaction, result) {
							    for (var i = 0; i < result.rows.length; i++) {
							        foodID = result.rows.item(i).FoodID;
									name = result.rows.item(i).Name;
							        calories = result.rows.item(i).Calories;
							        owner = result.rows.item(i).Owner;
									
							        opt = '<li value = "' + name + '" onclick="editFoodRecord(\'' + foodID + '\')">' + name +
											' - ' + calories + ' cal</li>';								
									
							        $("#ul_foodlist").append(opt);
							    }
							    $("#ul_foodlist").listview("refresh", true);
							},
							displayDbError
						);
					}
				);
			}
		);

        //Populates the Home page.
        $(document).on('pageshow', '#pg_home',
            function () {
                var record;
                var name = $("#current_profile").val();	
                
				db.transaction(
                    function (transaction) {
                        var sql = 'SELECT * FROM Profiles WHERE Name = ?';
						
                        transaction.executeSql(sql, [name],
                            function (transaction, result) {
                                if (result.rows.length > 0) {
                                    record = result.rows.item(0);

                                    $("#txt_profile_home_name").html(record.Name);
                                    $("#txt_profile_home_Wght").html("Current Weight: " + record.Wght + " lbs.");
                                    $("#txt_profile_home_Gwght").html("Goal Weight: " + record.GoalWght + " lbs.");
                                    $("#txt_profile_home_goal_calories").html("Goal Calories: " + record.GoalCals);
									
									if(record.Wght >= record.GoalWght){
										$("#goal").val("lose");										
									}
									else{
										$("#goal").val("gain");
									}
									
									setEatenAndRemaining(record.GoalCals);
                                }
                                else {
                                    alert("Profile for " + name + " not found");
                                    loadPage1();
                                }
                            },
                            displayDbError
                        );
                    }
                );
            }
        );

		
		/*
        The setEatenAndRemaining function sets the calories eaten field and calories remaining fields on the home page.
		
		@param   goalCals   the integer for the calorie amount goal that is used to determine the fields
        */
        function setEatenAndRemaining(goalCals) {
			db.transaction(
				function (transaction) {
					var profileName = document.getElementById("txt_profile_home_name").innerHTML;
					var dateString = getFormattedDateString("db", new Date());
					var sql = 'SELECT SUM(Calories) AS CalSum FROM Eaten WHERE EatenDate = ? AND ProfileName = ?  ';
					var record;
					var calsRemaining;					
					
					transaction.executeSql(sql, [dateString, profileName],
						function (transaction, result) {
							if (result.rows.length > 0) {
								record = result.rows.item(0);
								
								$("#txt_profile_home_calories_eaten").html(record.CalSum);
								
								if(record.CalSum == null){
									$("#txt_profile_home_calories_eaten").html("0");
								}
								
								if(record.CalSum < goalCals){
									calsRemaining = goalCals - record.CalSum;
									$("#txt_profile_home_calories_remaining").html(calsRemaining);			
								}
								else{
									calsRemaining = "0";
									$("#txt_profile_home_calories_remaining").html(calsRemaining);
								}
								
								setHomeAlert(calsRemaining);								
							}
							else {
								alert("No eaten record for " + profileName + " found");
							}
						},
						displayDbError
					);
				}
			);
        }
		
		
		/*
        The setHomeAlert function sets the alert to be displayed or not on home page.
		
		@param   cal   the integer representing difference between consumed and goal calories
        */
		function setHomeAlert(cal) {
			if(cal == "0" && $("#goal").val() == "lose"){
				document.getElementById('p_exceed_home').style.display = 'block';
				document.getElementById('p_unmet_home').style.display = 'none';
			}			
			else if(cal != "0" && $("#goal").val() == "gain"){
				document.getElementById('p_unmet_home').style.display = 'block';
				document.getElementById('p_exceed_home').style.display = 'none';
			}
			else{				
				document.getElementById('p_exceed_home').style.display = 'none';
				document.getElementById('p_unmet_home').style.display = 'none';
			}			
		}		
		
		
        //Populates the Edit Profile page.
        $(document).on('pageshow', '#pg_profile',
            function () {
                var name = document.getElementById("txt_profile_home_name").innerHTML;
                var action = document.getElementById("profile_action").value;
                var record;
				
				//save the current profile name in the document in case it is changed
				document.getElementById("txt_old_profile_name").value = name;

                if (action == 'update') {
                    db.transaction(
                        function (transaction) {
                            var sql = 'SELECT * FROM Profiles WHERE Name = ?';

                            transaction.executeSql(sql, [name],
                                function (transaction, result) {
                                    if (result.rows.length > 0) {
                                        record = result.rows.item(0);

                                        document.getElementById("txt_profile_name").value = record.Name;
                                        document.getElementById("nmbr_age").value = record.Age;
                                        document.getElementById("nmbr_feet").value = record.FtHght;
                                        document.getElementById("nmbr_inches").value = record.InHght;
                                        document.getElementById("nmbr_weight").value = record.Wght;
                                        document.getElementById("nmbr_goal_weight").value = record.GoalWght;
                                        document.getElementById("nmbr_sms_number").value = record.SMSNumber;

                                        //Load select menu with recorded exercise level
                                        $('#slct_level').val(record.ExerciseLevel).attr('selected', true).selectmenu("refresh", true);

                                        if (record.Gender == 'm') {
                                            $("#rdio_male").prop("checked", true).checkboxradio("refresh");
                                        }
                                        else if (record.Gender == 'f') {
                                            $("#rdio_female").prop("checked", true).checkboxradio("refresh");
                                        }
                                    }
                                    else {
                                        loadPage1();
                                    }
                                }, displayDbError
                            );
                        }
                    );
                }
            }
        );

		
        /*
        The onDeviceReady function calls the function that creates tables and displays the app start page.
        */
        function onDeviceReady() {
            //dropTables();
            createTables();

            $(document).delegate("#pg_page1", "pageshow",
                function () {
                    console.log("Device Ready");
                }
            );
        }


        /*
        To be used during development only!!!!!!!!!!!!!
        */
        function dropTables() {
            db.transaction(
                function (transaction) {
                //    var sql = 'DROP TABLE Profiles;';
                 //   transaction.executeSql(sql);
                    sql = 'DROP TABLE Foods;';
                    transaction.executeSql(sql);
                    sql = 'DROP TABLE Eaten;';
                    transaction.executeSql(sql);
                }
            );
            alert("tables have been dropped");
        }


        /*
        The createTables function creates the tables needed for the app.
        */
        function createTables() {
            db.transaction(
                function (transaction) {
                    transaction.executeSql(
                        'CREATE TABLE IF NOT EXISTS Profiles ' +
                        '       (Name TEXT NOT NULL PRIMARY KEY, ' +
                        '        Gender BOOLEAN NOT NULL, ' +
                        '        Age INTEGER NOT NULL, ' +
                        '        FtHght INTEGER NOT NULL, ' +
                        '        InHght INTEGER NOT NULL, ' +
                        '        Wght INTEGER NOT NULL, ' +
                        '        GoalWght INTEGER NOT NULL, ' +
                        '        ExerciseLevel TEXT NOT NULL, ' +
                        '        GoalCals INTEGER NOT NULL, ' +
                        '	     EmailAddress TEXT,  ' +
                        '	     SMSNumber INTEGER) '
                    );
                }
            );
            db.transaction(
                 function (transaction) {
                     transaction.executeSql(
                        'CREATE TABLE IF NOT EXISTS Foods ' +
                        '       (FoodID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, ' +
						'        Name TEXT NOT NULL, ' +
                        '        Owner TEXT NOT NULL, ' +
                        '        Calories INTEGER NOT NULL, ' +
						'		 UNIQUE (Name, Owner)) '
                     );
                 }
             );
            db.transaction(
				function (transaction) {
				    transaction.executeSql(
						'CREATE TABLE IF NOT EXISTS Eaten ' +
						'       (ID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, ' +
						'        ProfileName TEXT NOT NULL, ' +
						'        FoodName TEXT NOT NULL,' +
						'        Type TEXT, ' +
						'        Calories INTEGER NOT NULL,' +
						'        EatenDate DATE NOT NULL) '
					);
				}
			);
        }


        /*
        The displayDbError function is generic for displaying db error.
        */
        function displayDbError(transaction, err) {
            alert("DB error : " + err.message);
            return true;
        }


        /*
        The loadEmptyProfilePage function loads an empty profile screen.
        */
        function loadEmptyProfilePage() {
            document.getElementById("profile_action").value = "add";

            //Adding the changeHash: false to avoid an issue with the iframe
            $.mobile.changePage("#pg_profile", { transition: "none", changeHash: "false" });

            //reset the form
            resetProfileForm();
        }


        /*
        The loadProfileHome function loads the selected profile into the home page.
        */
        function loadProfileHome() {
            var name = $("#slct_profile").find(":selected").text();
			
			//Determine whether to notify user of input issue or to change the page to home page 
            if (document.getElementById("slct_profile").length == 1) {
                alert("No profile has been entered.\nPlease enter new profile.");
            }
            else if (name == "Profile Menu") {
                alert("No profile is selected.");                
            }
            else {
				//Set the current profile only if no profile is current since otherwise it is already set
				if($("#current_profile").val() == ""){
					$("#current_profile").val(name);				
				}
				
                //Adding the changeHash: false to avoid an issue with the iframe
                $.mobile.changePage("#pg_home", { transition: "none", changeHash: "false" });
            }
			
			$.mobile.activePage.find('.ui-btn-active').removeClass('ui-btn-active ui-focus');
        }


        /*
		The saveToSD function saves to external SD card or internal memory if no card present 
		a snapshot of current caolrie intake and profile information.
		*/
        function saveToSD() {
            db.transaction(
                function (transaction) {
                    var profileName = document.getElementById("txt_profile_home_name").innerHTML; //for the profile pertaining to infrormation being saved
                    var age; //for age related to profile
                    var weight = document.getElementById("txt_profile_home_Wght").innerHTML; //for current weight indicated on home page for profile information being saved
                    var goalWght = document.getElementById("txt_profile_home_Gwght").innerHTML; //for goal weight indicated on home page for profile information being saved
                    var exerciseLevel; //for exercise level related to profile
                    var goalCals = document.getElementById("txt_profile_home_goal_calories").innerHTML; //for goal calories indicated on home page for profile information being saved
                    var caloriesEaten = document.getElementById("txt_profile_home_calories_eaten").innerHTML; //for calories eaten indicated on home page for profile information being saved
                    var caloriesRem = document.getElementById("txt_profile_home_calories_remaining").innerHTML; //for calories remaining indicated on home page for profile information being saved
                    var date = new Date(); //for date being saved
                    var time = date.toLocaleTimeString(); //set time sting of time being saved
                    var record; //for results to of information related to profile
                    var infoStr; //for holding information concatenation
                    var sql = 'SELECT * FROM Profiles WHERE Name = ?'; //for query information related to profile
                    transaction.executeSql(sql, [profileName],
                        function (transaction, result) {
                            var filename; //for the file name to be saved as

                            if (result.rows.length > 0) {
                                record = result.rows.item(0);
                                age = record.Age;
                                exerciseLevel = record.ExerciseLevel;
                                filename = profileName + ".txt";

                                //Concatenate string that will be written in text file on SD card
                                infoStr = '\n_______________________________\n' + date.toLocaleDateString() + ' ' + time + '\n\n' +
                                profileName + '\nAge: ' + age + '\nExercise Level: ' + exerciseLevel + '\n' + weight +
                                '\n' + goalWght + '\n' + goalCals + '\nCalories Eaten: ' +
                                caloriesEaten + '\nCalories Remaining: ' + caloriesRem;// Build the information string

                                //Get filsystem with indicated parameters
                                window.requestFileSystem(LocalFileSystem.PERSISTENT, 1024 * 1024, writeFile, displayFsError);

                                /*
                                The writeFile function writes the information to file.
                                */
                                function writeFile(fs) {
                                    fs.root.getFile(filename, { create: true },
                                        function (entry) {

                                            entry.createWriter(function (fileWriter) {
                                                fileWriter.onwriteend = function (e) {
                                                    alert('Saved to SD card:\n' + infoStr);
                                                };

                                                fileWriter.onerror = function (e) {
                                                    alert("Save to SD card failed.\nPlease insure SD card is in device and mounted.");
                                                };

                                                fileWriter.seek(fileWriter.length); //start writing at EOF

                                                fileWriter.write(infoStr); //write information to file on SD card

                                            }, displayFsError);
                                        }, displayFsError
                                    );
                                }

                                /*
                                The displayFsError function displays file system error.
                                */
                                function displayFsError(err) {
                                    alert("FS error : " + err.toString());
                                    return true;
                                }
                            }
                            else {
                                loadPage1();
                            }
                        },
                        displayDbError
                    );
                }
            );
        }


        /*
        The loadPage1 function changes page to page 1.
        */
        function loadPage1() {
			//$("#current_profile").val("");
			
            //Adding the changeHash: false to avoid an issue with the iframe
            $.mobile.changePage("#pg_page1", { transition: "none", changeHash: "false" });
        }


        /*
        The loadEditProfile function loads the selected profile into the edit profile page.
        */
        function loadEditProfile() {
            document.getElementById("profile_action").value = "update";

            //Adding the changeHash: false to avoid an issue with the iframe
            $.mobile.changePage("#pg_profile", { transition: "none", changeHash: "false" });
        }


        /*
        The saveProfile function saves or updates a profile record.
        */
        function saveProfile() {
            var formError = getProfileFormError();
            var name = document.getElementById("txt_old_profile_name").value;
			var action = document.getElementById("profile_action").value;
			
            if (formError == "" &&  action == "update") {
                //request confirmation
                var replace = confirm("Are you sure you want to update the profile for " + name + ". ");

                //update the profile record if confirmed
                if (replace == true) {
                    processProfileRegistration("update");                    
                }
            }
            else if (formError == "") {
                //insert the profile record
				processProfileRegistration("insert");
            }
            else {
                //notify user of input error
                alert("Profile Input Error: \n\n" + formError);
            }
        }
		
		
		/*
        The processProfileRegistered checks the registered name against the db for 
		unique name violation and inserts or updates the the profile if no constraint 
		violation is found using the string passed in to indicate which action to perform.
		
		@param   action   a string either insert or update to indicate the desired action to perform
        */
        function processProfileRegistration(action) {
		
			db.transaction(
				function (transaction) {
					var sql = 'SELECT * FROM Profiles WHERE Name = ?';
					var profileName = $("#txt_profile_name").val();
					var oldProfileName = $("#txt_old_profile_name").val();
					var foundName = "";
					
					transaction.executeSql(sql, [profileName],
						function (transaction, result) {
							if (result.rows.length > 0 && profileName != oldProfileName) {								
								alert("Profile Update Aborted:\nA profile with that name already exists.");
							}
							else{ 
								if(action == "update"){									
									updateProfileRecord();									
								}
								
								if(action == "insert"){
									insertProfile();									
								}
								
								$("#current_profile").val(profileName);
							}
						}, displayDbError
					);
				}
			);
		}
		

        /*
        The getProfileFormError function gets profile form error for given input and returns "" or a string indicating error. 
		
		@return   a string that is either empty or contains error element(s)
        */
        function getProfileFormError() {
            var profileName = document.getElementById("txt_profile_name").value;
            var male = document.getElementById("rdio_male");
            var female = document.getElementById("rdio_female");
            var age = document.getElementById("nmbr_age").value;
            var ftHeight = document.getElementById("nmbr_feet").value;
            var inHeight = document.getElementById("nmbr_inches").value;
            var weight = document.getElementById("nmbr_weight").value;
            var goalWght = document.getElementById("nmbr_goal_weight").value;
            var exerciseLevel = document.getElementById("slct_level").value;
            var smsNumber = document.getElementById("nmbr_sms_number").value;
			var errorStr = "";

            if (profileName == "" || profileName == null) {               
				errorStr = errorStr + "Profile Name is invalid.\n";
            }

            if (!male.checked && !female.checked) {                
				errorStr = errorStr + "Gender is not selected.\n";
            }

            if (isNaN(age) || age <= 0 || age > 125 || age != parseInt(age)) {              
				errorStr = errorStr + "Age is invalid.\n";
            }

            if (isNaN(ftHeight) || ftHeight <= 0 || ftHeight > 10 || ftHeight != parseInt(ftHeight)) {               
				errorStr = errorStr + "Foot height is invalid.\n";
            }

            if (isNaN(inHeight) || inHeight < 0 || inHeight > 11 || inHeight == "" || inHeight != parseInt(inHeight)) {               
				errorStr = errorStr + "Inch height is invalid.\n";
            }

            if (isNaN(weight) || weight <= 0 || weight > 3000 || weight != parseInt(weight)) {               
				errorStr = errorStr + "Weight is invalid.\n";
            }

            if (isNaN(goalWght) || goalWght <= 0 || goalWght > 3000 || goalWght != parseInt(goalWght)) {               
				errorStr = errorStr + "Goal Weight is invalid.\n";
            }
			
            if (smsNumber != "" && smsNumber != null){
				if (!smsNumber.match(/^\d+$/) || smsNumber.length != 10) {               
					errorStr = errorStr + "SMS Number is invalid.\n";
				}
			}
			
			if (exerciseLevel == "none") {               
				errorStr = errorStr + "Exercise Level is not selected.\n";
            }
			
            return errorStr;
        }		
	

        /*
        The updateProfileRecord function updates a profile record in the database.
        */
        function updateProfileRecord() {
			var oldProfileName = $("#txt_old_profile_name").val();
            var profileName = $("#txt_profile_name").val().trim();
            var age = $("#nmbr_age").val();
            var ftHght = $("#nmbr_feet").val();
            var inHght = $("#nmbr_inches").val();
            var wght = $("#nmbr_weight").val();
            var goalWght = $("#nmbr_goal_weight").val();
            var exerciseLevel = $("#slct_level").val();
            var smsNumber = $("#nmbr_sms_number").val();
            var gender;
			
			
            if ($("#rdio_male").is(':checked')) {
                gender = "m";
            }
            else if ($("#rdio_female").is(':checked')) {
                gender = "f";
            }

            var goalCals = calcCal(wght, goalWght, gender, age, (Number(ftHght * 12) + Number(inHght)), exerciseLevel);
			
			//Update the profile record
            db.transaction(
                function (transaction) {
                    var sql = 'UPDATE Profiles ' +
								'SET Name = ?, Gender = ?, Age = ?, FtHght = ?, InHght = ?, Wght = ?, ' +
                                'GoalWght = ?, ExerciseLevel = ?, GoalCals = ? ,SMSNumber = ?' +
                                'WHERE Name = ?';

                    transaction.executeSql(sql, [profileName, gender, age, ftHght, inHght, wght, goalWght, exerciseLevel, goalCals, smsNumber, oldProfileName],
                        function () {
                            alert("Profile is updated.");
							$.mobile.changePage("#pg_home", { transition: "none", changeHash: "false" });
                        },
                        displayDbError
                    );
                }
            );
			
			//Update the Foods records for this profile
			db.transaction(
				function(transaction) {
					var sql = 'UPDATE Foods ' +
								'SET Owner = ? WHERE Owner = ?';
								  
					transaction.executeSql(sql, [profileName, oldProfileName],
						function () {
							//alert("Foods records for " + profileName + " have been updated");
						},
						displayDbError
					);
				}
			);
			
			//Update the Foods Eaten records for this profile
			db.transaction(
				function(transaction) {
					var sql = 'UPDATE Eaten ' +
								'Set ProfileName = ? WHERE ProfileName = ?';
								  
					transaction.executeSql(sql, [profileName, oldProfileName],
						function () {
							//alert("Foods Eaten records for " + profileName + " have been updated");
						},
						displayDbError
					);
				}
			);
        }	
		

        /*
        The insertProfile function inserts a profile into the database.
        */
        function insertProfile() {
            var name = $("#txt_profile_name").val().trim();;
            var age = $("#nmbr_age").val();
            var ftHght = $("#nmbr_feet").val();
            var inHght = $("#nmbr_inches").val();
            var wght = $("#nmbr_weight").val();
            var goalWght = $("#nmbr_goal_weight").val();
            var exerciseLevel = $("#slct_level").val();
            var smsNumber = $("#nmbr_sms_number").val();
            var gender;

            if ($("#rdio_male").is(':checked')) {
                gender = "m";
            }
            else if ($("#rdio_female").is(':checked')) {
                gender = "f";
            }

            var goalCals = calcCal(wght, goalWght, gender, age, (Number(ftHght * 12) + Number(inHght)), exerciseLevel);

            db.transaction(
                function (transaction) {
                    var sql = 'INSERT INTO Profiles(Name, Gender, Age, FtHght, InHght, Wght, GoalWght, ExerciseLevel, GoalCals, SMSNumber) ' +
								'VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?); ';
								
                    transaction.executeSql(sql, [name, gender, age, ftHght, inHght, wght, goalWght, exerciseLevel, goalCals, smsNumber],
                        function () {
                            alert("Profile is saved");
				
							loadPage1();
                        },
                        displayDbError
                    );
                }
            );
        }


        /*
        The deleteProfile function deletes a file from the system if it exists.
        */
        function deleteProfile() {
            var name = $("#txt_profile_name").val();

            //request delete confirmation
            var dlte = confirm("Are you sure you want to delete the profile?");

            //delete if confirmed
            if (dlte == true) {
                //delete the profile record from the database
                deleteProfileRecord();

                //reset the form
                resetProfileForm();

                loadPage1();
            }
        }


        /*
        The deleteProfileRecord function removes a profile record from the database.
        */
        function deleteProfileRecord() {
            var name = $("#txt_profile_name").val();

			db.transaction(
				function (transaction) {
					var sql = 'DELETE FROM Profiles WHERE Name = ?; '; 

					transaction.executeSql(sql, [name],
						function () {
							//alert("Profile deleted");
						},
						displayDbError
					);
				}
			);
			
			//Delete the food records for the profile
			db.transaction(
				function (transaction) {
					var sql = 'DELETE FROM Foods WHERE Owner = ?';
					transaction.executeSql(sql, [name],
						function () {
						    //alert("Foods Deleted For Profile " + name);
						},
						displayDbError
					);
				}
			);
			
			//Delete the foodsEaten records for the profile
			db.transaction(
				function (transaction) {
					var sql = 'DELETE FROM Eaten WHERE ProfileName = ?; ';

					transaction.executeSql(sql, [name],
						function () {
							//alert("Foods Eaten Deleted For Profile " + name);
						},
						displayDbError
					);
				}
			);
        }


        /*
        The resetProfileForm function clears the fields of the Profile form.
        */
        function resetProfileForm() {

            //clear all text fields
            $('#frm_profile input[type="text"]').each(function () {
                $(this).val("");
            });

            //reset all number fields
            $('#frm_profile input[type="number"]').each(function () {
                $(this).val("");
            });

            //uncheck radio buttons
            $("#rdio_male").prop("checked", false).checkboxradio("refresh");
            $("#rdio_female").prop("checked", false).checkboxradio("refresh");

            //reset exercise level select menu
            $('#slct_level').val('none').attr('selected', true).selectmenu("refresh", true);
        }


        /*
        The loadFoodsEaten function changes page to Foods Eaten page.
        */
        function loadFoodsEaten() {
            //Adding the changeHash: false to avoid an issue with the iframe
            $.mobile.changePage("#pg_foodseaten", { transition: "none", changeHash: "false" });
        }


        /*
        The loadNewFood function changes page to the Manage Foods page.
        */
        function loadNewFood() {
            //Adding the changeHash: false to avoid an issue with the iframe
            $.mobile.changePage("#pg_managefoods", { transition: "none", changeHash: "false" });
        }


        /*
		The saveAndAdd function saves the food input and ...
		*/
        function saveAndAdd() {
            $("#selected_food").val($("#txt_food_name").val() + "," + $("#nmbr_calories").val());
			var formError = getManageFoodsFormError(); //for Manage Foods form validity
			
            if (formError == "") {

                $.mobile.changePage("#pg_type_dialog", { transition: "none", changeHash: "false" });

                if (document.getElementById("food_action").value == "update" && document.getElementById("update_food").value != "") {
                    updateFoodRecord(document.getElementById("update_food").value);
                }
                else {
                    //insert the profile record
                    insertFood();
                }

                //reset the form
                resetFoodForm();

                $.mobile.activePage.find('.ui-btn-active').removeClass('ui-btn-active ui-focus');
            }
            else {
                alert("Food Input Error: \n\n" + formError);

                $.mobile.activePage.find('.ui-btn-active').removeClass('ui-btn-active ui-focus');
            }
        }


		/*
		The saveFood function calls the getManageFoodsFormError function,
		and records food if the input is valid
		*/
        function saveFood() {
            var formError = getManageFoodsFormError(); //for Manage Foods form validity

            if (formError == "") {
                if (document.getElementById("food_action").value == "update" && document.getElementById("update_food").value != "") {
                    updateFoodRecord(document.getElementById("update_food").value);
                }
                else {
                    //insert the food record
                    insertFood();
                }

                //reset the form
                resetFoodForm();

                $.mobile.changePage("#pg_managefoods", { allowSamePageTransition: true, transition: "none", changeHash: "false" });
            }
            else {
                //Error message
                alert("Food Input Error: \n\n" + formError);
				
                $.mobile.activePage.find('.ui-btn-active').removeClass('ui-btn-active ui-focus');
            }
        }


        /*
        The getManageFoodsFormError function gets Manage Foods form error for 
		given input and returns "" or a string indicating error. 
        */
        function getManageFoodsFormError() {
            var foodName = document.getElementById("txt_food_name").value;
            var calories = document.getElementById("nmbr_calories").value;
            var errorStr = "";

            if (foodName == "" || foodName == null) {
                errorStr = errorStr + "Name is invalid.\n";
            }

            if (isNaN(calories) || calories < 0 || calories > 3000 || calories == "" || calories != parseInt(calories)) {
              errorStr = errorStr + "Calories is invalid.\n";
            }

            return errorStr;
        }


        /*
		The insertFood function inserts a new food into the database.
		*/
        function insertFood() {
            var owner = document.getElementById("txt_profile_home_name").innerHTML; //for recording whose food to display when meal planning
            var name = $("#txt_food_name").val().trim();
            var calories = $("#nmbr_calories").val();

            db.transaction(
				function (transaction) {
				    var sql = 'INSERT INTO Foods(Name, Owner, Calories) ' +
							  ' VALUES(?, ?, ?) ';

				    transaction.executeSql(sql, [name, owner, calories],
						function () {
						    alert("Food saved");
						},
						function displayDbError(transaction, err) {
						    alert("Food Save Aborted:\nA food with that name already exists.");
						}
					);
				}
			);
        }


        /*
        The resetFoodForm function clears the inputs of the Manage Foods form.
        */
        function resetFoodForm() {

            //clear all text fields
            $('#frm_managefoods input[type="text"]').each(function () {
                $(this).val("");
            });

            //clear all number fields
            $('#frm_managefoods input[type="number"]').each(function () {
                $(this).val("");
            });
        }


        /*
        The deleteFood function records action intention to delete.
        */
        function deleteFood() {
            document.getElementById("food_action").value = "delete";

            document.getElementById('div_foodlist').style.display = 'block';
        }


        /*
        The editFood function records action intention to update and displays 
		food list view pertaining to profile.
        */
        function editFood() {
            document.getElementById("food_action").value = "update";

            document.getElementById('div_foodlist').style.display = 'block';
        }


        /*
		The editFoodRecord function edits a food record in the database.
		
		@param   foodId   the integer related to the food for editing 
		*/
        function editFoodRecord(foodId) {
            var owner = document.getElementById("txt_profile_home_name").innerHTML; //for the profile related to the food
                
			db.transaction(
				function (transaction) {
					var record;
					var sql = 'SELECT * FROM Foods WHERE FoodID = ? ';
										
					transaction.executeSql(sql, [foodId],
						function (transaction, result) {
							if (result.rows.length > 0) {
								record = result.rows.item(0);
								
								if (document.getElementById("food_action").value == "update") {
									document.getElementById("update_food").value = record.Name;
									
									document.getElementById("txt_food_name").value = record.Name;
									document.getElementById("nmbr_calories").value = record.Calories;
									
									document.getElementById('div_foodlist').style.display = 'none';
								}
								else {
									var dlte = confirm("Are you sure you want to delete " + record.Name + "?");

									//delete if confirmed
									if (dlte == true) {
										//delete the food record from the database
										deleteFoodRecord(record.Name);

										//reset the form
										resetFoodForm();

										document.getElementById('div_foodlist').style.display = 'none';
										
										$.mobile.changePage("#pg_managefoods", { allowSamePageTransition: true, transition: "none", changeHash: "false" });
									}
								}
							}
						},
						displayDbError
					);
				}
			);           
        }


        /*
		The updateFoodRecord function updates a food record in the database.
		
		@param   name   the string representing the food's name for update
		*/
        function updateFoodRecord(name) {
            var foodName = document.getElementById("txt_food_name").value.trim();
            var calories = document.getElementById("nmbr_calories").value;
            var owner = document.getElementById("txt_profile_home_name").innerHTML; //to hold owner of the food

            db.transaction(
				function (transaction) {
				    var sql = 'UPDATE Foods ' +
						      'SET Name = ?, Owner = ?, Calories = ?' +
							  'WHERE Name = ? AND Owner = ?';

				    transaction.executeSql(sql, [foodName, owner, calories, name, owner],
						function () {
						    alert("Food is updated.");
						    document.getElementById("update_food").value = "";
						    document.getElementById("food_action").value = "";
						},
						displayDbError
					);
				}
			);
        }


        /*
		The deleteFoodRecord function removes a food record from the database.
		
		@param   name   the string representing the food's name for database deletion
		*/
        function deleteFoodRecord(name) {
			var owner = document.getElementById("txt_profile_home_name").innerHTML; //to hold owner of the food
			
            db.transaction(
				function (transaction) {
					var sql = 'DELETE FROM Foods WHERE Name = ? AND Owner = ?';
					transaction.executeSql(sql, [name, owner],
						function () {
						    document.getElementById("food_action").value = "";
						},
						displayDbError
					);
				}
			);
        }


        /*
        The calcCal function calculates the recommended daily calories for a user.
		
		Calculation used in the function can be found at:
		http://getfit.jillianmichaels.com/calculate-recommended-caloric-intake-1140.html
        */
        function calcCal(weight, goalWght, sex, age, height, activity) {
            var goalCals = 0;
			
            //Calculates BMR 
            if (sex == 'f') {
                goalCals = height * 4.7 + (4.3 * weight);
                goalCals = goalCals - (age * 4.7);
                goalCals = goalCals + 655;
            } else {
                goalCals = height * 12.7 + (weight * 6.23);
                goalCals = goalCals - (age * 6.8);
                goalCals = goalCals + 66;
            }
			
            //Calculates Caloric Value based on activity level 
            switch (activity) {
                case "sedentary":
                    goalCals = goalCals * 1.2;
                    break;
                case "light":
                    goalCals = goalCals * 1.3;
                    break;
                case "moderate":
                    goalCals = goalCals * 1.4;
                    break;
                case "heavy":
                    goalCals = goalCals * 1.5;
                    break;
            }
			
			//Adjusts for lose/gain weight
            if (goalWght < weight) {
                goalCals = goalCals - 500;
            }
            else if (goalWght > weight) {
                goalCals = goalCals + 500;
            }

            return goalCals.toFixed(0);
        }


        /*
		The sendSM function sends short message to SMS number related to profile
		*/
        function sendSM() {
            if (hasCellConnection()) {
                db.transaction(
                    function (transaction) {
                        var profileName = document.getElementById("txt_profile_home_name").innerHTML; //for the profile pertaining to infrormation being sent
                        var age; //for age related to profile
                        var weight; //for current weight for profile information being sent
                        var goalWght; //for goal weight for profile information being sent
                        var exerciseLevel; //for exercise level related to profile
                        var goalCals; //for goal calories for profile information being sent
                        var number; //SMS number for the profile
						var caloriesEaten = document.getElementById("txt_profile_home_calories_eaten").innerHTML; //for calories eaten indicated on home page for profile information being sent
                        var caloriesRem = document.getElementById("txt_profile_home_calories_remaining").innerHTML; //for calories remaining indicated on home page for profile information being sent
                        var today = new Date(); //for date sent
						var sentDateString = getFormattedDateString("header", today); //for string of date sent
                        var timeString = today.toLocaleTimeString();; //set time sting of time sent
                        var record; //for result of information related to profile
                        var message; //for holding information concatenation
                        var sql = 'SELECT * FROM Profiles WHERE Name = ?'; //for query information related to profile
                        transaction.executeSql(sql, [profileName],
							function (transaction, result) {
							    if (result.rows.length > 0) {
							        record = result.rows.item(0);
							        age = record.Age;
									weight = record.Wght;
									goalWght = record.GoalWght;
							        exerciseLevel = record.ExerciseLevel;
									goalCals = record.GoalCals;
							        number = record.SMSNumber;
									
							        if (number <= 1000000000) {
							            alert('Please enter a vaild 10 digit SMS number into the your profile' +
										' to send SMS message to that number');
							        } else {
							            //Concatenated string that will be sent using SMS
							            message = sentDateString + '\n' + timeString + '\n' + profileName + '\nAge: ' + age + '\nExercise Level: ' + exerciseLevel + '\nWeight: ' + weight +
										'\nGoal Weight: ' + goalWght + '\nGoal Calories: ' + goalCals + '\nCalories Eaten: ' +
										caloriesEaten + '\nCalories Remaining: ' + caloriesRem;

							            SmsPlugin.prototype.send(number, message, '',
											function () {
											    alert('Sent to ' + number + ':\n\n' + message);
											},
											function (e) {
											    alert('Message Failed: ' + e);
											}
										);
							        }
							    }
							}
						);
                    }
                );
            }
            else {
                alert('Cannot send text without cell service.\nTry sending again when you have cell service.');
            }
        }


        /*
		The hasCellConnection function returns true if the phone has cell service or returns false otherwise
		*/
        function hasCellConnection() {
            var connectionState = navigator.connection.type; //to hold the type of phone connection returned

            if (connectionState != '2g' && connectionState != '3g' && connectionState != '4g' && connectionState != 'cell') {
                return false;
            }
            else {
                return true;
            }
        }


        /*
		The loadHelp function changes page to the Help page.
        */
        function loadHelp() {
            $.mobile.changePage("#pg_help", { transition: "none", changeHash: "false" });
        }
    </script>
</head>
<body>
    <!--1st page begin-->
    <div data-role="page" id="pg_page1" data-theme="d" data-transition="none">

        <!--1st page header begin-->
        <div data-role="header" id="hdr_page1" data-position="fixed">
            <h1>Calorie Counter</h1>
            <input type="button" class="ui-btn-left" name="btn_help" id="btn_help" value="?" onclick="loadHelp()" />
        </div>
        <!--End 1st page header-->

        <!--1st page content begin-->
        <div data-role="content" id="cntnt_page1" style="text-align: center">
            <p>
                Select a profile from the drop down menu below and click 'Load Selected Profile', or click 'Enter New Profile'
            </p>
            <form action="profileselected">
                <select id="slct_profile" name="slct_profile" ></select>
                <div style="text-align: center;">
                    <img style="border-radius: 0px;" src="scales.jpg" width="300" height="190" alt="Scale Pic" />
                </div>
                <button type="button" id="btn_load_profile_home" name="btn_load_profile_home" onclick="loadProfileHome()">Load Selected Profile</button>
                <button type="button" id="btn_new_profile" name="btn_new_profile" onclick="loadEmptyProfilePage()">Enter New Profile</button>
                <input type="hidden" id="current_profile" value="" /> 
            </form>
        </div>
        <!--End 1st page content-->

        <!--1st page footer begin-->
        <div data-role="footer" id="ftrMain"></div>
        <!--End 1st page footer-->
    </div>
    <!--End 1st page-->


    <!--Profile page begin -->
    <div data-role="page" id="pg_profile" data-add-back-btn="true" data-theme="d">

        <!--Profile page header begin-->
        <div data-role="header" id="hdr_profile" data-position="fixed">
            <h1>Edit Profile</h1>
        </div>
        <!--End profile page header-->

        <!--Profile page content begin-->
        <div data-role="content" id="cntnt_profile">
            <form id="frm_profile" name="frm_profile" action="viewprofile">
                <div id="div_profile_name" data-role="fieldcontain">
                    Profile Name<br />
                    <input id="txt_profile_name" name="txt_profile_name" type="text" />
                    <label for="txt_profile_name"></label>
                </div>
                <div id="div_gender" data-role="fieldcontain">
                    Gender<br />
                    <fieldset data-role="controlgroup" data-type="horizontal">
                        <input type="radio" name="rdio_gender" id="rdio_male" value="male" />
                        <label for="rdio_male">Male</label>
                        <input type="radio" name="rdio_gender" id="rdio_female" value="female" />
                        <label for="rdio_female">Female</label>
                    </fieldset>
                </div>
                <div id="div_age" data-role="fieldcontain">
                    Age<br />
                    <input id="nmbr_age" name="nmbr_age" type="number" />
                    <label for="nmbr_age">yr.</label>
                </div>
                <div id="div_height" data-role="fieldcontain">
                    Height<br />
                    <input id="nmbr_feet" name="nmbr_feet" type="number" />
                    <label for="nmbr_feet">ft.</label>
                    <input id="nmbr_inches" name="nmbr_inches" type="number" />
                    <label for="nmbr_inches">in.</label>
                </div>
                <div id="div_weight" data-role="fieldcontain">
                    Weight<br />
                    <input id="nmbr_weight" name="nmbr_weight" type="number" />
                    <label for="nmbr_weight">lbs.</label>
                </div>
                <div id="div_goal_weight" data-role="fieldcontain">
                    Goal Weight<br />
                    <input id="nmbr_goal_weight" name="nmbr_goal_weight" type="number" />
                    <label for="nmbr_goal_weight">lbs.</label>
                </div>
                <!--	<div id="div_email_address" data-role="fieldcontain">
					Email Address<br />
					<input id="txt_email_address" name="txt_email_address" type="text" />
					<label for="txt_email_address"></label>
				</div> -->
                <div id="div_sms_number" data-role="fieldcontain">
                    SMS Number (optional)<br />
                    <input id="nmbr_sms_number" name="nmbr_sms_number" type="number" />
                    <label for="nmbr_sms_number"></label>
                </div>
                <div id="div_level">
                    Exercise Level<br />
                    <select id="slct_level" name="slct_level">
                        <option value="none"> </option>
                        <option value="sedentary">Sedentary</option>
                        <option value="light">Light</option>
                        <option value="moderate">Moderate</option>
                        <option value="heavy">Heavy</option>
                    </select>
                </div>
                <br />
                <button type="button" id="btn_save" onclick="saveProfile()">Save Profile</button>
                <button type="button" id="btn_delete" onclick="deleteProfile()">Delete Profile</button>
				<input type="hidden" id="profile_action" value="" />
				<input type="hidden" id="txt_old_profile_name" value="" />
            </form>
        </div>
        <!--End profile page content-->

        <!--Profile page footer begin-->
        <div data-role="footer" id="ftr_profile"></div>
        <!--End profile page footer-->
    </div>
    <!--End profile page-->


    <!--Home page begin-->
    <div data-role="page" id="pg_home" data-add-back-btn="true" data-theme="d" data-transition="none">
	
        <!--Home page header begin-->		
        <div data-role="header" id="hdr_home" data-position="fixed">
            <h1 id='txt_profile_home_name'></h1>
        </div>
        <!--End home page header-->

        <!--Home page content begin-->
        <div data-role="content" id="cntnt_home">
            <form id="frm_home" name="frm_home" action="viewhome">
                <div id="div_date_time" style="text-align: center">
                    <script type="text/javascript">
                        var date = new Date();

                        document.write(date.toLocaleDateString() + "<br />");
                        document.write("<span id=\"time\"></span>");

                        function currentTime() {
                            var date = new Date();
                            var time = date.toLocaleTimeString();

                            $("#time").html(time); //time is shown here
                            setTimeout("currentTime()", 1000); //current time displays every second
                        }
						
                        currentTime();
                    </script>    
					<input type="hidden" id="goal" value="" />
                </div>
				<hr />
                <p id='txt_profile_home_Wght'>lbs.</p>
                <hr />
                <p id='txt_profile_home_Gwght'>Lbs</p>
                <hr />
				<p id="p_exceed_home" style="background-color: red; color: white; text-align: center; display: none">Goal Calories Exceeded
                </p>
				<p id="p_unmet_home" style="background-color: red; color: white; text-align: center; display: none">Goal Calories Not Satisfied
                </p>
                <p id="txt_profile_home_goal_calories"></p>
                <hr />
                <p>Calories Eaten: 
                <span id="txt_profile_home_calories_eaten"></span></p>
                <hr />
                <p>Calories Remaining:
				<span id="txt_profile_home_calories_remaining"></span></p>
                <hr />
            </form>
        </div>
        <button type="button" id="btn_food_consume" onclick="loadFoodsEaten()">Manage Calorie Intake</button>
        <button type="button" id="btn_existing_profile" onclick="loadEditProfile()">Edit Profile Information</button>
        <button type="button" id="btn_save_to_sdcard" onclick="saveToSD()">Save To SD Card</button>
        <button type="button" id="btn_test_email_sms" onclick="sendSM()">Send To SMS Number</button>
        <button type="button" id="btn_return_begin" onclick="loadPage1()">Exit Profile</button>
        <!--End home page content-->

        <!--Home page footer begin-->
        <div data-role="footer" id="ftr_home"></div>
        <!--End home page footer-->
    </div>
    <!--End home page-->


    <!--Foods Eaten page begin-->
    <div data-role="page" id="pg_foodseaten" data-theme="d" data-transition="none">
	
        <!--Foods Eaten page header begin-->
        <div data-role="header" id="hdr_foodseaten" data-position="fixed">
            <h1>Foods Eaten</h1>
            <a href="#pg_home" data-role="button" class="ui-btn-left" data-rel="back" id="btn_back_eaten" data-icon="arrow-l">Back</a>
			<a href="#pg_home" data-role="button" class="ui-btn-right" data-iconpos="right" id="btn_goto_home" data-icon="home" onclick="loadProfileHome()">Home</a>
        </div>
        <!--End foods eaten page header -->

        <!--Foods Eaten page date header begin-->
        <div data-role="header" id="hdr_date">
            <h1 id='txt_eaten_date'>01/01/0001</h1>
            <input type="button" data-role="button" class="ui-btn-left" name="btn_date_previous" id="btn_date_previous"
                data-icon="arrow-l" data-iconpos="notext" value="previous" onclick="changeDate('previous')" />
            <input type="button" data-role="button" class="ui-btn-right" name="btn_date_next" id="btn_date_next"
                data-icon="arrow-r" data-iconpos="notext" value="next" onclick="changeDate('next')" />
        </div>
        <!--End foods eaten page header -->

        <!--Foods Eaten page content begin-->
        <div data-role="content" id="cntnt_foodseaten">
            <div id="div_select_eaten" style="text-align: center">
                <form id="frm_foodseaten" name="frm_foodseaten" action="selectfoods">
					<input type="button" data-role="button" id="btn_reset_date"  value = "Reset Date" onclick="resetFoodsEatenDate()" />
					<button type="button" id="btn_enter_new_food" onclick="loadNewFood()">Manage Foods</button>
                    <a href="#pg_eaten_dialog"  data-role="button" data-rel="dialog" data-transition="none">Add To Calories</a>					
                </form>
				<p id="p_exceed_foodseaten" style="background-color: red; color: white; text-align: center; display: none">Goal Calories Exceeded
				</p>
				<p id="p_unmet_foodseaten" style="background-color: red; color: white; text-align: center; display: none">Goal Calories Not Satisfied
				</p>
				Calories Remaining: <span id="spn_foodseaten_calories_remaining"></span>				
            </div>            		
			<hr />
            <div id="div_eaten_list" style="text-align: center">
                Select a food from the menus below to remove from meal plan.<br />
				<div class="ui-bar ui-bar-d">Breakfast</div>
				<ul data-role="listview" id="breakfastEaten" data-inset="true"></ul>
				<div class="ui-bar ui-bar-d">Lunch</div>
				<ul data-role="listview" id="lunchEaten" data-inset="true"></ul>
				<div class="ui-bar ui-bar-d">Dinner</div>
				<ul data-role="listview" id="dinnerEaten" data-inset="true"></ul>
				<div class="ui-bar ui-bar-d">Snacks</div>
				<ul data-role="listview" id="snacksEaten" data-inset="true"></ul>
            </div>
        </div>
        <!--End foods eaten page content -->

        <!--Foods Eaten page footer begin-->
        <div data-role="footer" id="ftr_foodseaten"></div>
        <!--End foods eaten page footer -->
    </div>
    <!--End foods eaten page-->


    <!--Type Dialog page begin -->
    <div data-role="dialog" id="pg_type_dialog" data-theme="d" data-transition="none">
	
        <!--Type Dialog page header begin-->
        <div data-role="header" id="hdr_type_dialog">
            <h2>Meal Selection</h2>
        </div>
        <!--Type Dialog help page header-->

        <!--Type Dialog page content begin-->
        <div data-role="content" id="cntnt_type_dialog" style="text-align: center">
            <ul data-role="listview" id="ul_typeslist">
                <li  onclick="addSelectedToEaten('breakfast')">Breakfast</li>
                <li  onclick="addSelectedToEaten('lunch')">Lunch</li>
                <li  onclick="addSelectedToEaten('dinner')">Dinner</li>
                <li  onclick="addSelectedToEaten('snacks')">Snack</li>
            </ul>
        </div>
        <!--End Type Dialog page content-->
    </div>
    <!--End type dialog page-->


    <!--Food Eaten Dialog page begin -->
    <div data-role="dialog" id="pg_eaten_dialog" data-theme="d" data-transition="none">

        <!--Food Eaten Dialog page header begin-->
        <div data-role="header" id="hdr_eaten_dialog" data-position="fixed">
            <h2>Food Selection</h2>
            <input type="button" data-role="button" class="ui-btn-right" name="btn_home_eaten" id="btn_home_eaten"
                data-icon="Home" value="Home" data-iconpos="right" onclick="loadProfileHome()" />
        </div>
        <!--End type dialog page header-->

        <!--Eaten Dialog page content begin-->
        <div data-role="content" id="cntnt_eaten_dialog" style="text-align: center">
            <a href="#pg_eatenfoods" data-role="button" data-rel="back" id="btn_back_to_eaten" onclick="loadFoodsEaten()">Cancel Selection</a>
            <br />
            <ul data-role="listview" id="ul_eatenlist" data-filter="true"> </ul>
            <input type="hidden" id="selected_food" value="" />
        </div>
        <!--End Type Dialog page content-->
    </div>
    <!--End Type Dialog page-->


    <!--Manage Foods page begin-->
    <div data-role="page" id="pg_managefoods" data-theme="d" data-transition="none">

        <!--Manage Foods page header begin-->
        <div data-role="header" id="hdr_managefoods" data-position="fixed">
            <h1>Manage Foods</h1>
            <a href="#pg_foodseaten" data-role="button" class="ui-btn-left" data-rel="back" id="btn_back_manage_foods" data-icon="arrow-l">Back</a>
            <a href="#pg_home" data-role="button" class="ui-btn-right" data-iconpos="right" id="btn_go_home" data-icon="home" onclick="loadProfileHome()">Home</a>
        </div>
        <!--End manage foods page header-->

        <!--Manage Foods page content begin-->
        <div data-role="content" id="cntnt_managefoods">
            <form id="frm_managefoods" name="frm_managefoods" action="foodentered">
                <div id="div_food_name" data-role="fieldcontain">
                    Name:<br />
                    <input id="txt_food_name" name="txt_food_name" type="text" />
                    <label for="txt_food_name"></label>
                </div>
                <div id="div_calories" data-role="fieldcontain">
                    Calories:<br />
                    <input id="nmbr_calories" name="nmbr_calories" type="number" />
                    <label for="nmbr_calories"></label>
                </div>
                <div id="div_manage_foods_buttons" data-role="fieldcontain" style="text-align: center">
                    <button type="button" id="btn_save_and_add" onclick="saveAndAdd()">Save And Add To Calories</button>
                    <fieldset data-role="controlgroup" data-type="horizontal">
                        <input type="button" name="btn_record_food" id="btn_record_food" value="Save" onclick="saveFood()" />
                        <label for="btn_record_food">Save Food</label>
                        <input type="button" name="btn_edit_food" id="btn_edit_food" value="Edit" onclick="editFood()" />
                        <label for="btn_edit_food">Edit Food</label>
                        <input type="button" name="btn_delete_food" id="btn_delete_food" value="Delete" onclick="deleteFood()" />
                        <label for="btn_delete_food">Delete Food</label>
                        <input type="hidden" id="food_action" value="" />
                        <input type="hidden" id="update_food" value="" />
                    </fieldset>
                </div>
                <div id="div_foodlist" data-role="fieldcontain" style="display: none">
                    <p style="text-align: center">
                        Select from the list below the food for edit/delete.</p>
                    <ul data-role="listview" id="ul_foodlist" data-filter="true" data-filter-reveal="true" data-inset="true">
                    </ul>
                </div>
            </form>
        </div>
        <!--End manage foods page content-->

        <!--Manage Foods page footer begin-->
        <div data-role="footer" id="ftr_managefoods"></div>
        <!--End manage foods page footer -->
    </div>
    <!--End manage foods page-->


    <!--Help page begin -->
    <div data-role="page" id="pg_help" data-theme="d" data-transition="none" >

        <!--Help page header begin-->
        <div data-role="header" id="hdr_help" data-position="fixed">
            <h1>Help</h1>
			<a href="#pg_page1" data-role="button" class="ui-btn-left" data-rel="back" id="btn_back_help" data-icon="arrow-l">Back</a>
        </div>
        <!--End help page header-->

        <!--Help page content begin-->
        <div data-role="content" id="cntnt_help">
			<h3 style="text-align:center" >App Start Page</h3>
			<p><span  style="color:blue" >Profile Menu</span><br />
			Registers the profile name that the user wants to use for this session</p>
			<p><span  style="color:blue" >Load Selected Profile</span><br />
			Opens the Profile Home page that allows the user to see summary and access other app features</p>
			<p><span  style="color:blue" >Enter New Profile</span><br />
			Opens the Edit Profile page that allows the user to register a new profile</p>			
			<hr />
			<h3 style="text-align:center" >Edit Profile Page</h3>
			<p><span  style="color:blue" >Profile Name</span><br />
			Registers Profile Name (Required)</p>
			<p><span  style="color:blue" >Gender</span><br />
			Registers Gender (Required)</p>
			<p><span  style="color:blue" >Age</span><br />
			Registers Age (Required)</p>
			<p><span  style="color:blue" >Weight</span><br />
			Registers Weight (Required)</p>
			<p><span  style="color:blue" >Goal Weight</span><br />
			Registers Goal Weight (Required)</p>
			<p><span  style="color:blue" >SMS Number</span><br />
			Registers SMS Number (Optional)</p>
			<p><span  style="color:blue" >Exercise Level Menu</span><br />
			Registers Exercise Level (Required)</p>
			<p><span  style="color:blue" >Save Profile</span><br />
			Saves/Updates the registered profile and opens the Profile Home page</p>
			<p><span  style="color:blue" >Delete Profile</span><br />
			Deletes the registered profile and opens the App Start page upon deletion</p>
			<hr />
			<h3 style="text-align:center" >Profile Home Page</h3>
			<p><span  style="color:blue" >Manage Calorie Intake</span><br />
			Opens the Foods Eaten page that allows the user to add/remove foods to calorie intake</p>
			<p><span  style="color:blue" >Edit Profile Information</span><br />
			Opens the Edit Profile page that allows the user to edit/delete the current profile</p>
			<p><span  style="color:blue" >Save To SD Card</span><br />
			Saves a snapshot summary, related to the current profile, to SD Card, if available, or saves it to internal memory otherwise</p>
			<p><span  style="color:blue" >Send To SMS Number</span><br />
			Sends a snapshot summary (text - carrier charges may apply) related to the current profile to the SMS number registered for the current profile</p>
			<p><span  style="color:blue" >Exit Profile</span><br />
			Exits to the App Start page</p>
			<hr />
			<h3 style="text-align:center" >Foods Eaten Page</h3>
			<p><span  style="color:blue" >Left/Right Arrows</span><br />
			Changes the page's date to allow the user to plan for other days</p>
			<p><span  style="color:blue" >Reset Date</span><br />
			Resets the page's date to the current date</p>
			<p><span  style="color:blue" >Manage Foods</span><br />
			Opens the Manage Foods page that allows the user to save, edit, and delete foods</p>
			<p><span  style="color:blue" >Add To Calories</span><br />
			Opens the Foods Selection dialog that allows the user to select food for the date listed on the page</p>
			<p><span  style="color:blue" >Breakfast, Lunch, Dinner, and Snacks </span><br />
			Displays the menus registered for the date listed on the page and allows the user to remove foods from any menu</p>
			<hr />
			<h3 style="text-align:center" >Manage Foods Page</h3>
			<p><span  style="color:blue" >Name</span><br />
			Registers the name for a food (Required)</p>
			<p><span  style="color:blue" >Calories</span><br />
			Registers the calories for a food (Required)</p>
			<p><span  style="color:blue" >Save And Add To Calories</span><br />
			Saves/Updates current information registered on page and opens the Meal Selection dialog to register food for the date listed on Foods Eaten page </p>
			<p><span  style="color:blue" >Save</span><br />
			Saves/Updates current information registered on page</p>
			<p><span  style="color:blue" >Edit</span><br />
			Opens a list view for the user to select which food to edit</p>
			<p><span  style="color:blue" >Delete</span><br />
			Opens a list view for the user to select which food to delete</p>
			<p><span  style="color:blue" >Manage Foods List</span><br />
			Registers the food that the user wants to edit/delete</p>
			<hr />
			<h3 style="text-align:center" >Food Selection Dialog</h3>
			<p><span  style="color:blue" >Cancel Selection</span><br />
			Cancels a food selection for the date listed on Foods Eaten page</p>
			<p><span  style="color:blue" >Food Selection List</span><br />
			Registers the food that the user selects for the date listed on Foods Eaten page</p>
			<hr />
			<h3 style="text-align:center" >Meal Selection Dialog</h3>
			<p><span  style="color:blue" >Meal Selection List</span><br />
			Registers which meal menu that the user wants the selected food for the date listed on Foods Eaten page</p>
        </div>
        <!--End help page content-->
		
		<!--Help page footer begin-->
        <div data-role="footer" id="ftr_help"></div>
        <!--End help page footer -->
    </div>
    <!--End help page-->
</body>
</html>
